package com.flutter.jl_plugin.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.os.ParcelUuid;
import android.util.Log;

import com.flutter.jl_plugin.JlPlugin;
import com.flutter.jl_plugin.JlSdkPlugin;
import com.flutter.jl_plugin.OpusTools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jieli.bluetooth.bean.base.BaseParameter;
import com.jieli.bluetooth.bean.base.CommandBase;
import com.jieli.bluetooth.bean.command.custom.CustomCmd;
import com.jieli.bluetooth.bean.device.eq.EqInfo;
import com.jieli.bluetooth.bean.device.status.BatteryInfo;
import com.jieli.bluetooth.bean.parameter.CustomParam;
import com.jieli.bluetooth.constant.Command;
import com.jieli.bluetooth.constant.StateCode;
import com.jieli.bluetooth.impl.rcsp.RCSPController;
import com.jieli.bluetooth.interfaces.rcsp.callback.BTRcspEventCallback;
import com.jieli.bluetooth.utils.CHexConver;
import com.jieli.bluetooth.utils.JL_Log;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;

public class MyBTRcspEventCallback extends BTRcspEventCallback {
    String TAG="MyBTRcspEventCallback";
    @Override
    public void onConnection(BluetoothDevice device, int status) {
        super.onConnection(device, status);
        JL_Log.i(TAG, "-onConnection- device : " + device + ", status = " + status);
        Map<String, Object> map = new HashMap<>();
        map.put("connectStatus",status);
        map.put("address",device.getAddress());
        map.put("name",device.getName());
        JlPlugin.Companion.getChannel().invokeMethod("onConnection",map);
    }


    @Override
    public void onEqChange(BluetoothDevice device, EqInfo eqInfo) {
        super.onEqChange(device, eqInfo);
        JL_Log.i(TAG,"onEqChange->"+eqInfo.toString());
        JL_Log.i(TAG,"当前线程->"+Thread.currentThread().getName());
        Map<String, Object> map = new HashMap<>();
        map.put("mode", eqInfo.getMode());
        map.put("value", toIntList(eqInfo.getValue()));
        map.put("freqs", toIntList(eqInfo.getFreqs()));
        map.put("dynamic", eqInfo.isDynamic());
        map.put("count", eqInfo.getCount());
        JlPlugin.Companion.getChannel().invokeMethod("onEqChange",map);
    }

    private List<Integer> toIntList(byte[] arr) {
        List<Integer> list = new ArrayList<>();
        for (byte b : arr) {
            list.add((int) b & 0xFF); // 保证转为无符号
        }
        return list;
    }

    private List<Integer> toIntList(int[] arr) {
        List<Integer> list = new ArrayList<>();
        for (int i : arr) {
            list.add(i);
        }
        return list;
    }


    @Override
    public void onBondStatus(BluetoothDevice device, int status) {
        super.onBondStatus(device, status);
        JL_Log.i(TAG, "-onBondStatus- device : " + device + ", status = " + status);
        Map<String, Object> map = new HashMap<>();
        map.put("onBondStatus",status);
        map.put("address",device.getAddress());
        map.put("name",device.getName());
        JlPlugin.Companion.getChannel().invokeMethod("onBondStatus",map);
    }

    @Override
    public void onDeviceCommand(BluetoothDevice device, CommandBase cmd) {
        super.onDeviceCommand(device, cmd);
        if (cmd.getId() == Command.CMD_EXTRA_CUSTOM) {
            Map<String, Object> map = new HashMap<>();
            JL_Log.i(TAG, "-onDeviceCommand cmd = " + cmd.toString());

            CustomCmd customCmd= (CustomCmd) cmd;
            CustomParam param = customCmd.getParam();
            boolean isNeedResponse = cmd.getType() == CommandBase.FLAG_HAVE_PARAMETER_AND_RESPONSE
                    || cmd.getType() == CommandBase.FLAG_NO_PARAMETER_AND_RESPONSE;
            if(null == param){
                if(isNeedResponse){
                    byte[] responseData = new byte[0]; //可以设置回复的数据
                    customCmd.setParam(new CustomParam(responseData));
                    customCmd.setStatus(StateCode.STATUS_SUCCESS);
                    RCSPController.getInstance().sendCommandResponse(device, customCmd, null); //发送命令回复
                    //接收到设备发送的自定义数据: 无参数。错误的命令数据格式
                    JL_Log.e(TAG,"接收到设备发送的自定义数据: 无参数。错误的命令数据格式");
                    return;
                }
            }
            byte[] data = param.getData(); //自定义数据
            JL_Log.e(TAG,"接收到设备发送的自定义数据"+CHexConver.byte2HexStr(data));
            if(isNeedResponse){
                byte[] responseData = new byte[0];
                customCmd.setParam(new CustomParam(responseData));
                customCmd.setStatus(StateCode.STATUS_SUCCESS);
                RCSPController.getInstance().sendCommandResponse(device, customCmd, null); //发送命令回复
            }
            String hex=CHexConver.byte2HexStr(data);
            map.put("address",device.getAddress());
            map.put("name",device.getName());
            Map<String, Object> cmdMap = new HashMap<>();
            cmdMap.put("type",cmd.getType());
            cmdMap.put("receiveCmd",hex);
            cmdMap.put("byte",data);
            map.put("cmd",cmdMap);
            FlutterEngine engine = FlutterEngineCache.getInstance().get("my_engine");
            if(hex.startsWith("07 FE")){
                JlPlugin.Companion.getChannel().invokeMethod("onDeviceCommandDecode",map);
            }else{
                JlPlugin.Companion.getChannel().invokeMethod("onDeviceCommand",map);

            }


        }
    }

    boolean isStart=false;

    public  void creatOpus(){
        String path=JlPlugin.Companion.getActivity().getCacheDir().getPath()+"/aaa_steam.opus";
        createFileStream(path);

    }

    private static FileOutputStream foutStream;
    private void createFileStream(String filePath) {
        closeFileStream();
        try {
            foutStream = new FileOutputStream(filePath);
            isStart=true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private  void closeFileStream() {
        if (null == foutStream) return;
        try {
            foutStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            foutStream = null;
        }
    }


    @Override
    public void onBatteryChange(BluetoothDevice device, BatteryInfo batteryInfo) {
        super.onBatteryChange(device, batteryInfo);
        JL_Log.i(TAG, "-onBatteryChange- device : " + device + ", batteryInfo = " + batteryInfo.toString());
//        Map<String, Object> map = new HashMap<>();
//        map.put("batteryInfo",batteryInfo.getBattery());
//        map.put("address",device.getAddress());
//        map.put("name",device.getName());
//        JlPlugin.Instance.channel.invokeMethod("onBatteryChange",map);
    }


    @Override
    public void onPhoneCallStatusChange(BluetoothDevice device, int status) {
        super.onPhoneCallStatusChange(device, status);
        Map<String, Object> map = new HashMap<>();
        map.put("status",status);
        JlPlugin.Companion.getChannel().invokeMethod("onPhoneCallStatusChange",map);
    }
}
